import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useStorage } from '@vueuse/core'
import type { UserInfo, LoginParams } from '@/types/auth'
import { login, getUserInfo, logout } from '@/api/auth'
import { useTagsStore } from './tags'
import { useLayoutStore } from './layout'
import { usePermissionStore } from './permission'

export const useUserStore = defineStore('user', () => {
  const token = useStorage('token', '')
  const userInfo = ref<UserInfo | null>(null)

  // 登录
  async function handleLogin(params: LoginParams) {
    try {
      const { token: newToken } = await login(params)
      token.value = newToken
    } catch (error) {
      throw new Error('登录失败')
    }
  }

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const info = await getUserInfo()
      userInfo.value = info
    } catch (error) {
      throw new Error('获取用户信息失败')
    }
  }

  // 退出登录
  async function handleLogout() {
    try {
      await logout()
      // 清除用户相关状态
      token.value = ''
      userInfo.value = null

      // 清除其他store的状态
      const tagsStore = useTagsStore()
      const layoutStore = useLayoutStore()
      const permissionStore = usePermissionStore()

      tagsStore.$reset()
      layoutStore.$reset()
      permissionStore.$reset()

      // 清除localStorage
      localStorage.clear()

      return Promise.resolve()
    } catch (error: any) {
      // 即使接口调用失败，也要清除本地状态
      token.value = ''
      userInfo.value = null
      localStorage.clear()
      return Promise.resolve()
    }
  }

  return {
    token,
    userInfo,
    login: handleLogin,
    getUserInfo: fetchUserInfo,
    logout: handleLogout
  }
})
